package com.example.firstapp.storeData

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.firstapp.R
import com.example.firstapp.databinding.ActivityStoreData1Binding
import java.io.BufferedReader
import java.io.BufferedWriter
import java.io.IOException
import java.io.InputStreamReader
import java.io.OutputStreamWriter

class storeData1 : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_store_data1)

        val binding = ActivityStoreData1Binding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.storeData1Submit.setOnClickListener {
            val input = binding.storeData1Input.text.toString()
            save(input)
        }
        binding.storeData1Get.setOnClickListener {
            binding.storeData1Show.text = show()
        }
    }
    private fun save(input:String){
        try {
            // 获取一个output对象 命名datass 模式为覆盖模式MODE_PRIVATE
            val output = openFileOutput("datass", Context.MODE_PRIVATE)
            // 构建一个OutputStreamWriter对象
            // 使用OutputStreamWriter构建出一个BufferedWriter对象
            val writer = BufferedWriter(OutputStreamWriter(output))
            println(input)
            //writer.write(input)
            // writer.close() 必须关闭流 否则数据可能只在内存缓冲区中，没有写入磁盘文件
            // 可以使用use自动关闭 安全输入输出
            writer.use {
                it.write(input)
            }
        } catch (e:IOException){
            e.printStackTrace()
        }
    }
    private fun show():String{
        val content = StringBuilder()
        try {
            println("show")
            val input = openFileInput("datass")
            val reader = BufferedReader(InputStreamReader(input))
            reader.use {
                reader.forEachLine {
                    content.append(it)
                }
            }

        } catch (e:IOException){
            e.printStackTrace()
        }
        return content.toString()
    }
}